package login

import (
	"fmt"
	"net/http"

	"github.com/gin-contrib/sessions"
	"github.com/gin-gonic/gin"
	"src/myaccount.go/src/model"
)

func CreateUser(c *gin.Context) {
	user := model.Users{}

	user.Username = c.PostForm("username")
	user.Password = c.PostForm("password")

	var enable string
	enable = c.PostForm("enable")

	if enable == "on" {
		user.Enable = 1
	} else {
		user.Enable = 0
	}

	fmt.Println(user)

	if err := user.Create(); err != nil {
		fmt.Println(err)
		c.JSON(http.StatusOK, gin.H{
			"error":   1,
			"message": "创建失败",
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"error":   0,
		"message": "创建成功",
	})
}

func ChangePass(c *gin.Context) {

	username := c.PostForm("username")
	password := c.PostForm("password")

	if username == "" {
		session := sessions.Default(c)
		username = session.Get("userkey").(string)
	}

	user, err := model.GetUser(username)
	if err != nil {
		fmt.Println(err)
		c.JSON(http.StatusOK, gin.H{
			"error":   1,
			"message": "查询失败",
		})
		return
	}

	if user.Password == model.Encrypt(password) {
		c.JSON(http.StatusOK, gin.H{
			"error":   1,
			"message": "与原密码重复，无需修改",
		})
		return
	} else {
		if err := user.UpdatePass(password); err != nil {
			fmt.Println(err)
			c.JSON(http.StatusOK, gin.H{
				"error":   1,
				"message": "修改密码失败",
			})
			return
		}
		c.JSON(http.StatusOK, gin.H{
			"error":   0,
			"message": "密码修改成功",
		})
	}

}
